package com.xneure.database.sql.handler;

import java.util.List;
import com.xneure.database.metaobject.FieldMetaObject;
import com.xneure.database.metaobject.TableMetaObject;
import com.xneure.utils.ObjectUtil;

public class OutreachProvider{
	private Object value;// 持有者值
	private String outreach;// 关联字段
	private Object outreachValue;// 关联结果
	private SqlHandler sqlHandlerl;
	private StringBuilder sb = new StringBuilder();

	public OutreachProvider(Object obj,FieldMetaObject val,SqlHandler sqlHandlerl){
		outreachValue = ObjectUtil.getFieldValue(obj,val.getField());
		outreach = val.getAnnotation().value().toLowerCase();
		this.sqlHandlerl = sqlHandlerl;
		this.sqlHandlerl.setSqlAspect(new SqlAspect(){
			@Override
			public boolean discardNull(TableMetaObject metaObject,FieldMetaObject field){
				return field.getName().toLowerCase().equalsIgnoreCase(outreach) == false;
			}

			@Override
			public Object processValue(TableMetaObject table,FieldMetaObject field,Object _value){
				if(field.getName().toLowerCase().equals(outreach)){
					if(null == value){
						FieldMetaObject tmp = table.getFields().get(val.getAnnotation().relation());
						if(null != tmp){
							value = tmp.getValue(obj);
						}
					}
					return value;
				}
				return SqlAspect.super.processValue(table,field,_value);
			}
		});
	}

	public String buildSql(){
		sb.setLength(0);
		if(outreachValue instanceof List<?>){
			((List<?>)outreachValue).forEach(v-> {
				sqlHandlerl.resetParam();
				sqlHandlerl.build(v);
				sb.append(sqlHandlerl.getSql()).append(";\r\n");
			});
		}else{
			sqlHandlerl.resetParam();
			sqlHandlerl.build(outreachValue);
			sb.append(sqlHandlerl.getSql()).append(";\r\n");
		}
		return sb.toString();
	}
}
